import { defineStore } from "pinia";
import { signInPwd,getUserInfo,getUserMenu } from "../../api/user/index";
import type { LoginForm,LoginResponseData } from "../../api/user/type";
import local from "../../utils/local"
import {constantRouterMap  }  from "@/router/router"
import  router from "@/router/index"
import type {  RouteRecordRaw } from "vue-router"

//定义小仓库 state的数据类型
export interface UserState {
  token: string | null,
  menuRouter: RouteRecordRaw[],
  DtmenuRouter: RouteRecordRaw[],
  userInfo:Object
}

// 创建小仓库
const useUserstate = defineStore("User", {
  //存储数据的地方
  state: ():UserState => {
    return {
      token:local.getItem('token')||' ',
      menuRouter:constantRouterMap,//菜单路由
      DtmenuRouter:[],
      userInfo:{}
    };
  },
  // 异步逻辑
  actions: {
    hasPermission(){

    },
    clear_token(){
      this.token = ''
      local.removeItem('token')
    },
    async userLogin(rufrom: LoginForm) {
      console.log(rufrom);
     const result:LoginResponseData = await signInPwd(rufrom);
        if(result.code===200){
            //仓库存一份
            this.token=(result.data.token as string)
            // 本地存储
            local.setItem('token',(result.data.token as string))
            return result
        }else{
           return Promise.reject(new Error(result.data.message))
        }   
    },
    async get_UserInfo(){
        const result:any = await getUserInfo();
        if(result.code===200){
            this.userInfo=result.data
            local.setItem('userInfo',(result.data.token as string))
            return result
        }else{
           return Promise.reject(new Error(result.data.message))
        }
    },
    async get_UserMenu(){
      const result:any = await getUserMenu();
        if(result.code===200){
            return result
        }else{
           return Promise.reject(new Error(result.data.message))
        }
    }
  },
  // 计算属性
  getters: {},
});

export default useUserstate;
